package com.yangcb.workrecord.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Random;
import java.util.List;


/**
 * ${DESCRIPTION}
 *
 * @author yangcb
 * @create 2017-10-09 14:12
 **/
public class MyRedistest {

    Logger logger = LoggerFactory.getLogger(MyRedistest.class);

    public static void main(String[] args) {

        final String watchkeys = "watchkeys";

        ExecutorService executor = Executors.newFixedThreadPool(20);//20个线程池并发数
        try {
            final Jedis jedis = new Jedis("127.0.0.1", 6379);
            jedis.set(watchkeys, "100");//设置起始的抢购数
            jedis.close();
            for (int i = 0; i < 1000; i++) {//设置1000个人来发起抢购
                executor.execute(new MyRunnable("user" + getRandomString(6)));
            }
        } finally {
            executor.shutdown();
        }
    }


    public static String getRandomString(int length) { //length是随机字符串长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

}


class MyRunnable implements Runnable {
    Logger logger = LoggerFactory.getLogger(MyRunnable.class);

    String watchkeys = "watchkeys";// 监视keys
    Jedis jedis = new Jedis("127.0.0.1", 6379);
    String userinfo;

    public MyRunnable() {

    }

    public MyRunnable(String userinfo) {
        this.userinfo = userinfo;
    }


    @Override
    public void run() {

        try {

            jedis.watch(watchkeys);//监视key
            String val = jedis.get(watchkeys);
            logger.info("------------>目前库存数量：{}", val);
            int valint = Integer.valueOf(val);
            if (valint <= 100 && valint >= 1) {

                Transaction tx = jedis.multi();//开启事务
                tx.incrBy(watchkeys, -1);
                List<Object> list = tx.exec();//提交事务，如果此时watchkeys被改动了，返回null

                if (list == null || list.size() == 0) {
                    String failuserifo = "fail" + userinfo;
                    String failinfo = "用户：" + failuserifo + "商品争抢失败，抢购失败";
                    logger.info("------------>FAIL：{}", failinfo);
                        /* 抢购失败业务逻辑 */
                    jedis.setnx(failuserifo, failinfo);
                } else {

                    for (Object succ : list) {
                        String succuserifo = "succ" + succ.toString() + userinfo;
                        String succinfo = "用户：" + succuserifo + "抢购成功，当前抢购成功人数:"
                                + (1 - (valint - 100));
                        logger.info("------------>SUCCESS：{}", succinfo);
                              /* 抢购成功业务逻辑 */
                        jedis.setnx(succuserifo, succinfo);
                    }

                }
            } else {
                String failuserifo = "kcfail" + userinfo;
                String failinfo1 = "用户：" + failuserifo + "商品被抢购完毕，抢购失败";
                logger.info("------------>FAIL：{}", failinfo1);
                jedis.setnx(failuserifo, failinfo1);
                return;
            }


        } catch (Exception e) {
            logger.info("秒杀异常:{}",e);
        } finally {
            jedis.close();
        }

    }
}


